
const readline = require('readline');
const { Sequelize } = require('sequelize');
const { copyFolder, runCommand, replaceContent, copyFile,readFile } = require('./util.js');
const fs = require('fs');
const path = require('path');


const sql_creatrqusertabel = "CREATE TABLE rquser (userid int NOT NULL AUTO_INCREMENT,  loginname varchar(45)  DEFAULT NULL,  loginpwd varchar(45)  DEFAULT NULL,  wxopenid varchar(45)  DEFAULT NULL, phone varchar(45)  DEFAULT NULL,  nickname varchar(45)  DEFAULT NULL,  regtime datetime DEFAULT NULL,  lastlogin datetime DEFAULT NULL,  headicon varchar(400)  DEFAULT NULL,  PRIMARY KEY (userid)) ;";

const sql_inserrquseradmin = "INSERT INTO rquser (loginname,loginpwd,nickname,headicon) VALUES ('admin','96e79218965eb72c92a549dd5a330112','管理员','https://res.wx.qq.com/mpres/zh_CN/htmledition/comm_htmledition/images/icon/login/mp_service_new767bae.png');";

var dbhost, dbname, dbuser, dbpassword;

function getDBinfo() {
    return new Promise((resolve, reject) => {
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });

        rl.question('请输入数据库地址: ', (host) => {
            dbhost = host;
            rl.question('请输入数据库名: ', (database) => {
                dbname = database;
                rl.question('请输入数据库用户名: ', (user) => {
                    dbuser = user;
                    rl.question('请输入数据库密码: ', (password) => {
                        dbpassword = password;
                        rl.close();
                        resolve();

                    });
                });
            });
        });
    });
}
function copyeDBTPL() {
    copyFolder('./tpl/dbcfg_tpl', './project/dbcfg')
    replaceContent('./project/dbcfg/dbconfig.js', /\$DBHOST\$/g, dbhost)
    replaceContent('./project/dbcfg/dbconfig.js', /\$DBNAME\$/g, dbname)
    replaceContent('./project/dbcfg/dbconfig.js', /\$DBUSER\$/g, dbuser)
    replaceContent('./project/dbcfg/dbconfig.js', /\$DBPWD\$/g, dbpassword)
}

async function generateDBModel() {
    const cmd = `cd ./project/dbcfg && npx sequelize-auto -h ${dbhost} -d ${dbname} -u ${dbuser} -x ${dbpassword} -p 3306`;
    console.log('生成数据库模型 start \n' + cmd);
    await runCommand(cmd)
        .then((stdout) => {
            console.log('命令执行成功:', stdout);
            console.log('生成数据库模型 end ');
        })
        .catch((error) => {
            console.error('命令执行失败:', error);
        });
}

function generateEggServer() {
    //根据DBmodel 生成 接口
    //copy server模版
    copyFolder('./tpl/eggserver_tpl', './project/eggserver');
    //copy 生成的db文件
    copyFolder('./project/dbcfg/', './project/eggserver/app/dbcfg/')
    var files = fs.readdirSync('./project/eggserver/app/dbcfg/models');
    const sequelize = new Sequelize(dbname, dbuser, dbpassword, {
        host: dbhost,
        dialect: 'mysql'
    })
    const DataTypes = require("sequelize").DataTypes;

    var routerconfig = '';

    files.forEach(file => {
        console.log("生成后台接口相关文件："+file);
        if (file == 'init-models.js' || file == 'rquser.js') {
            console.log('跳过init-models.js / rquser.js');

        } else {
            var _file = './project/eggserver/app/dbcfg/models/' + file;
            var _modle = require(_file);
            var model = _modle(sequelize, DataTypes);
            var tableName = model.tableName;
            var primaryKey = model.primaryKeyAttribute;

            //拼接egg路由
            routerconfig += `\n\n //${tableName}相关接口\n router.get('/${tableName}/list',controller.${tableName}.list);
                        router.post('/${tableName}/add', controller.${tableName}.add);
                        router.post('/${tableName}/update', controller.${tableName}.update);
                        router.get('/${tableName}/delete', controller.${tableName}.del);
                        router.get('/${tableName}/get', controller.${tableName}.get);`;

            // 生成service 
            fs.copyFileSync('./project/eggserver/app/service/servicejs.tpl', './project/eggserver/app/service/' + tableName + '.js');

            // 替换文件名
            replaceContent('./project/eggserver/app/service/' + tableName + '.js', /\$TABLE_NAME\$/g, tableName);
            replaceContent('./project/eggserver/app/service/' + tableName + '.js', /\$PRIMARYKEY\$/g, primaryKey);

            // 生成controller
            fs.copyFileSync('./project/eggserver/app/controller/controllerjs.tpl', './project/eggserver/app/controller/' + tableName + '.js');
            // 替换文件名
            replaceContent('./project/eggserver/app/controller/' + tableName + '.js', /\$TABLE_NAME\$/g, tableName); //替换表名
            replaceContent('./project/eggserver/app/controller/' + tableName + '.js', /\$PRIMARYKEY\$/g, primaryKey);//替换主键
        }

    });
    

    replaceContent('./project/eggserver/app/router.js', /\$ROUTERCFG\$/g, routerconfig);

}

function generatePureAdmin() {
    copyFolder('./tpl/pure-admin-tpl', './project/pureadmin');
    var files = fs.readdirSync('./project/eggserver/app/dbcfg/models');
    const sequelize = new Sequelize(dbname, dbuser, dbpassword, {
        host: dbhost,
        dialect: 'mysql'
    })
    const DataTypes = require("sequelize").DataTypes;
    files.forEach(file => {
        console.log("生成admin页面相关文件："+file);

        if (file == 'init-models.js' || file == 'rquser.js') {
            console.log('跳过init-models.js / rquser.js');
        } else {
            var _file = './project/dbcfg/models/' + file;
            var _modle = require(_file);
            var model = _modle(sequelize, DataTypes);
            var tableName = model.tableName;
            var primaryKey = model.primaryKeyAttribute;

            //生成页面VIEW
            var viewtplfolder = './tpl/pureadmin_tpl_comments/viewtpl/'
            var viewsFolder = './project/pureadmin/src/views/';
            copyFolder(viewtplfolder, viewsFolder + tableName + '/')
            var viewfolder = viewsFolder + tableName + '/';
            // 替换form属性 
            var attributes = model.getAttributes();

            var formstructs = '';
            var formitems = '';  //add.vue 使用
            var formitemsEDIT = ''; //detail.vue使用
            var listcolumns = '';
            for (var key in attributes) {
                var attribute = attributes[key];
                var type = attribute.type;
                var field = attribute.field;
                var comment = attribute.comment;
                // form 结构  主键暂不添加，后面根据新增页面还是详情页米爱你添加
                if(field == primaryKey){
                    formstructs += '\n'
                } else {
                    formstructs += field + ':"",\n'
                }

                // form item 结构
                var label = attribute.comment ? attribute.comment : field;
                if (field == primaryKey) {
                    //add.vue 主键不可输入
                    formitems += '\n';
                    //detail.vue 主键不可更改
                    formitemsEDIT +='<el-form-item label="'+label+'" class="form-item">'+
                    '<el-input v-model="dataForm.'+field+'" disabled="false" readonly placeholder="'+label+'" />'
                    +'</el-form-item>';
                } else {
                    formitems += '<el-form-item label="' + label + '">' +
                        '<el-input v-model="formData.' + field + '"/></el-form-item>' +
                        '\n';
                    formitemsEDIT +='<el-form-item label="'+label+'" class="form-item">'+
                    '<el-input v-model="dataForm.'+field+'" :disabled="!isEditMode" placeholder="'+label+'" />'
                    +'</el-form-item>';
                }


                // list 结构
                listcolumns += '<el-table-column prop="' + field + '" label="' + label + '" width="150" align="center"></el-table-column>';

            }
            //add.vue  form属性不增加主键

            replaceContent(viewfolder + 'add.vue', /\$FORMATTRIBUTE\$/g, formstructs);
            replaceContent(viewfolder + 'add.vue', /\$FORMITEM\$/g, formitems);
            replaceContent(viewfolder + 'add.vue', /\$TABLENAME\$/g, tableName);

            //list.vue
            replaceContent(viewfolder + 'list.vue', /\$PRIMARYKEY\$/g, primaryKey);
            replaceContent(viewfolder + 'list.vue', /\$LISTCOLUMN\$/g, listcolumns);
            replaceContent(viewfolder + 'list.vue', /\$TABLENAME\$/g, tableName);

            //detail.vue
 
            replaceContent(viewfolder + 'detail.vue', /\$TABLENAME\$/g, tableName);
            //详情页面data增加主键的属性
            formstructs = formstructs+primaryKey+':""';
            replaceContent(viewfolder + 'detail.vue', /\$FORMATTRIBUTE\$/g, formstructs);
            replaceContent(viewfolder + 'detail.vue', /\$EDITFORMITEM\$/g, formitemsEDIT);
            replaceContent(viewfolder + 'detail.vue', /\$PRIMARYKEY\$/g, primaryKey);

            //生成API
            var apitplpath = './tpl/pureadmin_tpl_comments/api_tpl.ts';
            var apifolder = './project/pureadmin/src/api/';
            copyFile(apitplpath, apifolder + tableName + '.ts')
            replaceContent(apifolder + tableName + '.ts', /\$TABLENAME\$/g, tableName);


            //生成路由
            var routertplpath = './tpl/pureadmin_tpl_comments/router_tpl.ts';
            var routerfolder = './project/pureadmin/src/router/modules/';
            copyFile(routertplpath, routerfolder + tableName + '.ts');
            replaceContent(routerfolder + tableName + '.ts', /\$TABLENAME\$/g, tableName);


        };
    });
}

function clearTMP() {
    // 获取当前工作目录
    const currentDir = process.cwd();
    // project文件夹的完整路径
    const projectDir = path.join(currentDir, 'project');

    // 检查project文件夹是否存在
    if (fs.existsSync(projectDir)) {
        try {
            // 使用递归删除目录
            fs.rmSync(projectDir, { recursive: true, force: true });
            console.log('project文件夹已成功删除');
        } catch (err) {
            console.error(`删除project文件夹时出错: ${err.message}`);
            process.exit(1);
        }
    } else {
        console.log('project文件夹不存在');
    }
}

function attachDBTable(){

    const sequelize = new Sequelize(dbname, dbuser, dbpassword, {
        host: dbhost,
        dialect: 'mysql'
    });
    sequelize.query(sql_creatrqusertabel).then(function (res) {
        console.log('creat rquser success: '+res);
        sequelize.query(sql_inserrquseradmin).then(function (res) {
            console.log('inser rquser admin success: '+res);
        });
    })
}

async function debug() {
    clearTMP();

    await getDBinfo();
    copyeDBTPL();
    attachDBTable();
    await generateDBModel();
    generateEggServer();
    generatePureAdmin();
    console.log('function debug end//////////////////////////////////////////////')
}




debug();










